package com.kun.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.common.enumType.LevelEnum;
import com.kun.common.constant.UserConstant;
import com.kun.common.service.RedisService;
import com.kun.common.util.StringUtils;
import com.kun.domain.TFollowingGroup;
import com.kun.service.service.*;
import com.kun.common.util.PasswordUtil;
import com.kun.domain.TUserInfo;
import com.kun.service.mapper.TUserMapper;
import com.kun.domain.TUser;
import com.kun.service.util.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.LocalDateTime;

@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {

    private final ITUserInfoService itUserInfoService;
    private final TokenService tokenService;
    private final ITFollowingGroupService itFollowingGroupService;
    private final ISysUserRoleService sysUserRoleService;
    private final RedisService redisService;


    public TUserServiceImpl(ITUserInfoService itUserInfoService, TokenService tokenService,
                            ITFollowingGroupService itFollowingGroupService, ISysUserRoleService sysUserRoleService,
                            RedisService redisService) {
        this.itUserInfoService = itUserInfoService;
        this.tokenService = tokenService;
        this.itFollowingGroupService = itFollowingGroupService;
        this.sysUserRoleService = sysUserRoleService;
        this.redisService = redisService;
    }

    /**
     * 添加用户
     */
    @Override
    @Transactional
    public boolean addUser(TUser tUser) {
        // 判断手机号是否注册
        Assert.isTrue(getUserByPhone(tUser.getPhone()) == null, "该手机号已注册");
        tUser.setPassword(PasswordUtil.encodePassword(tUser.getPassword()));
        LocalDateTime now = LocalDateTime.now();
        tUser.setCreateTime(now);
        tUser.setUpdateTime(now);
        boolean save = save(tUser);
        // 添加用户信息
        TUserInfo tUserInfo = new TUserInfo(tUser.getId(), UserConstant.DEFAULT_NICKNAME, UserConstant.DEFAULT_GENDER,
                UserConstant.DEFAULT_BIRTHDAY, now);
        boolean insert = itUserInfoService.insert(tUserInfo);
        // 为用户创建默认组
        TFollowingGroup tFollowingGroup = new TFollowingGroup(tUser.getId(),
                UserConstant.DEFAULT_FOLLOW_GROUP_NAME, UserConstant.DEFAULT_FOLLOW_GROUP_TYPE, LocalDateTime.now());
        boolean insert1 = itFollowingGroupService.insert(tFollowingGroup);
        // 为用户创建默认角色
        boolean addUserRole = sysUserRoleService.addUserRole(tUser.getId(), (long) LevelEnum.LEVEL_ONE.getValue());
        return save && insert && insert1 && addUserRole;
    }

    /**
     * 用户登录
     */
    @Override
    public String login(TUser tUser) {
        Assert.isTrue(tUser.getEmail() != null || tUser.getPhone() != null, "手机号和邮箱其一不能为空");
        TUser userByPhone = getUserByPhoneAndEmail(tUser.getPhone(), tUser.getEmail());
        Assert.isTrue(userByPhone != null, "当前用户不存在");
        boolean matches = PasswordUtil.matches(tUser.getPassword(), userByPhone.getPassword());
        Assert.isTrue(matches, "密码不正确");
        // 加密token
        return tokenService.getToken(userByPhone);
    }

    /**
     * 退出登录
     */
    @Override
    public void logout() {
        String uuid = UserContext.getUser().getUserInfo().getUuid();
        if (uuid != null) {
            String key = redisService.getKey(UserConstant.LOGIN_TOKEN_KEY + uuid);
            if (key != null) {
               redisService.delKey(key);
            }
        }
    }

    /**
     * 获取用户信息
     */
    @Override
    public TUser getInfo() {
        return UserContext.getUser();
    }

    /**
     * 修改用户密码手机号邮箱
     */
    @Override
    public Boolean updateUser(TUser tUser) {
        Long userId = UserContext.getUserId();
        tUser.setId(userId);
        return updateById(tUser);
    }

    /**
     * 根据用户ID查询
     */
    @Override
    public TUser getUserById(Long followingId) {
        return getById(followingId);
    }

    /**
     * 根据邮箱或者手机号查询
     */
    private TUser getUserByPhoneAndEmail(String phone, String email) {
        return lambdaQuery().eq(StringUtils.isNotEmpty(phone), TUser::getPhone, phone)
                .eq(StringUtils.isNotEmpty(email), TUser::getEmail, email).last("LIMIT 1").one();
    }

    /**
     * 根据手机号查找用户
     */
    public TUser getUserByPhone(String phone) {
        return lambdaQuery().eq(TUser::getPhone, phone).last("LIMIT 1").one();
    }

}
